package com.bjsxt.thread;

public class DrawMoneyThread {

    public static void main(String[] args) {
        Account account = new Account("1234",1000);
        new DrawThread("老公",account,800).start();
        new DrawThread("老婆",account,800).start();
    }
}

class Account{
    private String accountNo;
    private double balance;
    public String getAccountNo() {
        return accountNo;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    public double getBalance() {
        return balance;
    }

    public Account() {
    }

    public Account(String accountNo, double balance) {
        this.accountNo = accountNo;
        this.balance = balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
}

class DrawThread extends Thread{
    private Account account;
    private double drawmoney;
    public DrawThread(String name,Account account,double drawmoney){
        super(name);
        this.account=account;
        this.drawmoney =drawmoney;
    }
    @Override
    public void run() {  //在run方法加synthronized无效
        synchronized (this.account){
            if (this.account.getBalance()>=this.drawmoney){
                System.out.println(this.getName()+"取钱成功"+this.drawmoney);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.account.setBalance(this.account.getBalance()-this.drawmoney);
                System.out.println("余额为"+account.getBalance());
            }else {
                System.out.println(this.getName()+"余额不足，失败");
            }
        }
    }
}
